<!--
*  2021-03-15
* 样布列表
-->
<template>
  <div id="app" class="sample">
    <!-- 头部导航 -->
    <van-nav-bar
      ref="header"
      left-arrow
      title="样布数据"
      @click-left="onClickLeft"
      left-text="返回"
    >
      <template #right>
        <span @click="onClickRight" style="margin-right: 10px"
          ><van-icon name="plus" size="20"
        /></span>
        <span @click="onClickScan"><van-icon name="scan" size="20" /></span>
      </template>
    </van-nav-bar>
    <!-- 筛选 -->
    <van-search v-model="designNo" placeholder="请输入搜索关键词" />
    <!-- 滚动 -->
    <better-scroll
      class="public-scroll"
      :data="tableData"
      :totalPage="totalPage"
      :pulldown="true"
      @pulldown="onGetClothStoreCheck"
    >
      <van-cell-group v-show="tableData.length !== 0">
        <div v-for="(data, index) in tableData" :key="index">
          <van-cell
            :title="data.no"
            :label="data.name"
            class="start-cell"
            @click="onClickDetails(data)"
          >
            <template>
              <span>{{ data.colorNo }}</span>
              <span>{{ "¥" + data.price }}</span>
            </template>
          </van-cell>
        </div>
      </van-cell-group>
      <van-empty
        class="custom-image"
        image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
        v-show="tableData.length === 0"
        description="暂无数据"
      />
    </better-scroll>

    <!-- 详情 -->
    <!-- 筛选事项 -->
    <van-popup
      v-model="show"
      position="right"
      get-container="#app"
      :style="{ width: '100%', height: '100%' }"
    >
      <sample-edit
        :isShow="show"
        :row="row"
        @callReturn="onCancel"
        @onConfirmPrint="onConfirmPrint"
      />
    </van-popup>
  </div>
</template>

<script>
import { openWin, comeBack, getFloat } from "@/utils/index";
import { getClothSampleList } from "@/api/yarn";
import dayjs from "dayjs";
import { getMacAddress } from "@/utils/auth";

export default {
  name: "sample",
  data() {
    return {
      title: "",
      currentPage: 1,
      totalPage: 1,
      tableData: [],
      pageNum: 1,
      pageSize: 1000,
      show: false,
      designNo: "",
      dateTime: dayjs().format("YYYY-MM-DD"),
      minDate: new Date(dayjs().subtract(1, "year")),
      maxDate: new Date(),
      beginAt: dayjs().format("YYYY-MM-DD 00:00:00"),
      endAt: dayjs().format("YYYY-MM-DD 24:00:00"),
      totalNum: 0,
      id: "",
      row: {},
      printStatus: false,
      printRow: {},
    };
  },
  watch: {
    // 监听事件筛选
    dateTime() {
      this.onGetClothStoreCheck();
    },
    // 监听designNo
    designNo(newVal, oldVal) {
      // 防止input连续输入时，频繁发请求
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        // 异步请求
        if (oldVal !== newVal) {
          this.onGetClothStoreCheck();
        }
      }, 1000);
    },
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    getFloat,
    //初始化
    initFn(that) {
      that.onGetClothStoreCheck();
      if (getMacAddress()) {
        that.isEnabledBluetooth();
      } else {
        that.$toast.fail('如需打印，请退出登录选择打印机')
      }
      window.api.addEventListener({
        name:'viewdisappear'
      }, function() {
        window.api.closeWin();
      });
    },
    // 返回
    onClickLeft() {
      comeBack();
    },
    // 新增
    onClickRight() {
      openWin('sample-edit')
    },
    // 取消
    onCancel() {
      this.show = false;
    },
    // 扫码
    onClickScan() {
      const that = this;
      that.id = "";
      const zyHmsScan = api.require('zyHmsScan');
      zyHmsScan.openDefaultView({}, ret => {
        if(ret.status) {
          that.id = ret.result;
          that.onGetClothStoreCheck();
        }
      });
    },
    onClickDetails(data) {
      openWin("sample-edit", data);
    },
    //  样品列表
    onGetClothStoreCheck() {
      this.tableData = [];
      this.totalNum = 0;
      getClothSampleList(
        {
          pageNum: this.pageNum,
          pageSize: 100,
          id: this.id,
        },
        (res) => {
          if (this.id) {
            openWin('sample-edit', res.list[0])
          } else {
            this.tableData = res.list;
          }
        }
      );
    },
    // 判断蓝牙是否打开
    isEnabledBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .isEnabledBluetooth({}, (ret, err) => {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.connectBleByMacAddress();
            } else {
              that.openBluetooth();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 打开蓝牙
    openBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .openBluetooth({}, function (ret, err) {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.connectBleByMacAddress();
            }
          } else {
            that.listenBluetoothStatus();
          }
        });
    },
    // 监听蓝牙连接状态
    listenBluetoothStatus() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .listenBluetoothStatus({}, function (ret, err) {
          if (!err) {
            if (ret.status === "STATE_ON") {
              that.connectBleByMacAddress();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 查询打印机连接状态
    getConnectState() {
      const that = this;
      that.$toast({
        message: "正在打印",
        type: "loading",
        duration: 20000,
      });
      var obj = window.api.require("xGprinterPlus");
      var ret = obj.getConnectState();
      if (ret.status) {
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接
          that.$toast.clear();
          if (that.printStatus) {
            that.printLabel();
          }
        } else {
          // 未连接
          that.$toast({
            type: "fail",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      } else {
        // 未连接
        that.$toast({
          type: "fail",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddress();
          },
        });
      }
    },
    // 连接蓝牙
    connectBleByMacAddress(status) {
      const that = this;
      if (that.printStatus) {
        that.$toast({
          message: "初始化打印机",
          type: "loading",
          duration: 20000,
        });
      }
      var demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress(
        {
          macAddress: getMacAddress() ? getMacAddress().address : '',
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.message === "已连接") {
              that.connectionStatus = true;
              if (that.printStatus) {
                that.$toast({
                  type: "success",
                  message: "连接成功",
                  duration: 1500,
                  onClose: () => {
                    that.printLabel();
                  },
                });
              }
              if (status) {
                that.onClickAddStore();
              }
            } else if (ret.message === "连接失败") {
              that.connectionStatus = false;
              that.$toast({
                type: "fail",
                message: "初始化失败",
                duration: 1500,
              });
            } else {
              that.connectionStatus = false;
            }
          } else {
            that.$toast({
              type: "fail",
              message: err.msg,
              duration: 1500,
            });
          }
        }
      );
    },
    // 打印数据
    printLabel() {
      const that = this;
      var obj = window.api.require("xGprinterPlus");
      obj.printLabel(
        {
          rows: [
            {
              lineType: "size",
              width: 50,
              height: 70,
            },
            {
              lineType: "gap",
              data: 3,
            },
            {
              lineType: "cls",
            },
            {
              lineType: "image", //绘制图片
              x: 370,
              y: 10,
              data: that.logo, //支持fs:// widget://
            },

            {
              //绘制文本
              lineType: "text",
              x: 370,
              y: 130,
              rotation: 90,
              xscal: 1,
              yscal: 1.5,
              data: "领 先 工 ",
            },
            {
              //绘制文本
              lineType: "text",
              x: 380,
              y: 130 + 110,
              rotation: 90,
              xscal: 1,
              yscal: 2,
              data: "艺 多 ",
            },
            {
              //绘制文本
              lineType: "text",
              x: 370,
              y: 130 + 180,
              rotation: 90,
              xscal: 1,
              yscal: 1.5,
              data: "创 奇 迹 ",
            },
            // 产品编号
            {
              //绘制文本
              lineType: "text",
              x: 300,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "产品编号",
            },
            {
              //绘制文本
              lineType: "text",
              x: 270,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "ITEM NO",
            },
            {
              //绘制文本
              lineType: "text",
              x: 295,
              y: 120,
              rotation: 90,
              xscal: 1,
              yscal: 2,
              data: that.printRow.no.substr(0, 10),
            },
            // 克重
            {
              //绘制文本
              lineType: "text",
              x: 220,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "克  重",
            },
            {
              //绘制文本
              lineType: "text",
              x: 190,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "WEIGHT",
            },
            {
              //绘制文本
              lineType: "text",
              x: 215,
              y: 120,
              rotation: 90,
              xscal: 1,
              yscal: 2,
              data: that.printRow.greyMiWeight + "g/m",
            },
            // 成份
            {
              //绘制文本
              lineType: "text",
              x: 140,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "成  份",
            },
            {
              //绘制文本
              lineType: "text",
              x: 110,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "content",
            },
            {
              //绘制文本
              lineType: "text",
              x: 135,
              y: 120,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: that.printRow.composition,
            },
            // 名称
            {
              //绘制文本
              lineType: "text",
              x: 60,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "名称",
            },
            {
              //绘制文本
              lineType: "text",
              x: 30,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "NAME",
            },
            {
              //绘制文本
              lineType: "text",
              x: 55,
              y: 120,
              rotation: 90,
              xscal: 1,
              yscal: 2,
              data: that.printRow.name,
            },
            // 颜色/色号
            {
              //绘制文本
              lineType: "text",
              x: 300,
              y: 250,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "颜色/色号",
            },
            {
              //绘制文本
              lineType: "text",
              x: 270,
              y: 250,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "COLOR NO",
            },
            {
              //绘制文本
              lineType: "text",
              x: 295,
              y: 250 + 120,
              rotation: 90,
              xscal: 1,
              yscal: 2,
              data: that.printRow.colorNo,
            },
            // 幅宽
            {
              //绘制文本
              lineType: "text",
              x: 220,
              y: 250,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "幅 宽",
            },
            {
              //绘制文本
              lineType: "text",
              x: 190,
              y: 250,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "WIDTH",
            },
            {
              //绘制文本
              lineType: "text",
              x: 215,
              y: 250 + 120,
              rotation: 90,
              xscal: 1,
              yscal: 2,
              data: that.printRow.width + "cm",
            },
            {
              lineType: "qrcode", // 绘制qrcode
              x: 10,
              y: 400,
              level: "L", //L|M|H|Q
              cellwith: 5,
              rotation: 0, // 0|90|180|270
              data: that.printRow.id,
            },
          ],
        },
        function (ret, err) {
          if (ret.status) {
            that.printStatus = false;
            that.$toast.success("打印成功");
          } else {
            that.$toast({
              type: "fail",
              message: err.code + err.msg,
              duration: 1500,
              onClose: () => {
                that.connectBleByMacAddress();
              },
            });
          }
        }
      );
    },
    // 打印
    onConfirmPrint(data) {
      this.printStatus = data.printStatus;
      this.printRow = data.printRow;
      this.getConnectState();
    },
  },
};
</script>

<style lang="scss">
.sample {
  .van-search {
    position: relative;
    z-index: 999;
  }
  .public-scroll {
    height: calc(100vh - 125px);
    overflow: hidden;
    .van-cell {
      .van-cell__value {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        justify-content: flex-end;
      }
    }
  }
}
</style>

